from tool import Util
import pandas as pd
import baostock as bs

# 登陆接口
lg = bs.login()
# 显示登陆返回信息
print('login respond error_code:'+lg.error_code)
print('login respond  error_msg:'+lg.error_msg)

# 同时配置开始和结束时间：'sz.002455':'2021-01-08:2021-01-08'
security_dict = {'sh.000001':'','sz.399001':'','sz.399006':'','sh.000688':'','sh.600939':'',
                 'sz.002202':'','sz.300308':'','sh.600506':'','sz.002006':'','sz.002905':'',
                 'sz.300432':'','sh.600967':'','sz.002214':'','sz.002882':'','sh.603757':'',
                 'sz.002360':'','sz.002765':'','sz.000534':'','sz.000665':'','sz.002650':'',
                 'sz.000151':'','sz.301012':'','sz.300933':'','sz.002163':'','sz.300222':'',
                 'sh.688076':'','sz.300506':'','sh.600149':'','sz.300693':'','sh.603766':'',
                 'sz.300456':'','sz.300008':'','sz.300065':'','sz.002171':'','sz.002623':'',
                 'sz.002031':'','sh.603358':'','sz.000012':'','sz.000633':''}

security_list = security_dict.keys()

# index_list = ['KDJ_S','LWR_S','MACD_S','BRAR_S', 'LB_S','VRSI_S','MA_S','BOLL_S','OBV_S','MFI_S']
index_list = ['KDJ_S','WR_S','MACD_S', 'LB_S', 'BOLL_S','OBV_S','MFI_S']

# 从待选指标中不重复抽样5个指标
# 随机指标个数
select_num = len(index_list)
select_index = Util.listRandomChoice(index_list, select_num)

### 参数设置 ###
# # KDJ 统计的天数
# KDJ_N, KDJ_M1, KDJ_M2 = 8, 2, 5
# WR_N, WR_N1, WR_N2 = 12, 7, 9
# MACD_MID, MACD_LONG, MACD_SHORT, MACD_LONG2, MACD_LONG3 = 10, 26, 9, 47, 60
# BRAR_N = 26
# CYR_N, CYR_M = 13, 5
# LB_N = 6
# MACD_M1, MACD_M2 = 5, 10
# VRSI_M1, VRSI_M2, VRSI_M3 = 6, 12, 24
# MA_N = 5
# MA_LONG_N = 15
# BOLL_N, BOLL_M = 13, 7
# Boll_timeperiod, Boll_nbdevup, Boll_nbdevdn = 20, 2, 2
# OBV_TimePeriod = 37
# VOL_M1, VOL_M2 = 5, 20
# MFI_TimePeriod = 9
# ### 参数设置 end ###
#
# # 指标权重参数，初始时均为1
# weightDict = {'KDJ_S':[1], 'WR_S':[1],'MACD_S':[1],'LB_S':[1],'BOLL_S':[1],'OBV_S':[1],'MFI_S':[1]}
# # weightDict = {'KDJ_S':[0.121], 'WR_S':[0.111],'MACD_S':[0.145],'LB_S':[0.258],'BOLL_S':[0.127],'OBV_S':[0.111],'MFI_S':[0.127]}
# weightDictDF = pd.DataFrame(weightDict)
# # print(weightDictDF)


stock = pd.DataFrame()
final_result = pd.DataFrame()
for stockCode, testDate in security_dict.items():
    # 获取传过来的testDate
    testDateList = testDate.split(":")
    if len(testDateList) == 2:
        start_check_date = testDateList[0]
        end_check_date = testDateList[1]
    else:
        start_check_date = str(Util.getYesterday(int(200)))
        end_check_date = str(Util.getYesterday(1))

    print("股票代码为：" + stockCode + "， 数据测试开始时间为：" + str(start_check_date) + "， 数据测试结束时间为：" + str(end_check_date))


    # 获取前五日该指标值，从而找到该指标知期趋势
    # TODO 这个地方有个问题，就是如果是节假日，该数据可能获取不准，
    # check_date_before = util.getYesterday(int(i) + 5)
    # 获取前一交易日日线行情数据
    # adjustflag：复权类型，默认不复权：3；后复权: 1；前复权: 2。已支持分钟线、日线、周线、月线前后复权。
    stock_rs = bs.query_history_k_data_plus(stockCode,
                                      "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
                                      start_date=start_check_date, end_date=end_check_date,
                                      frequency="d", adjustflag="2")
    # 获取证券股票名称
    stock_basic_rs = bs.query_stock_basic(code=stockCode)

    #### 打印结果集 ####
    stock_dt = []
    stock_basic_dt =[]
    while (stock_rs.error_code == '0') & stock_rs.next() :
        # 获取一条记录，将记录合并在一起
        stock_dt.append(stock_rs.get_row_data())
    while (stock_basic_rs.error_code == '0') & stock_basic_rs.next():
        stock_basic_dt.append(stock_basic_rs.get_row_data())

    stockDF = pd.DataFrame(stock_dt, columns=stock_rs.fields)
    stockBasicDF = pd.DataFrame(stock_basic_dt, columns=stock_basic_rs.fields)
    # 将stockDF与stockBasicDF合并 根据stock_code
    result = pd.merge(stockDF, stockBasicDF, on=['code'], how='left')

    if stock.empty:
        stock = result
    else:
        stock = stock.append(result)
#### 登出系统 ####
bs.logout()
# 获取数据后对数据进行处理
# 数据处理，去除停牌日的数据，volume数据为空或0的行

stock = stock.dropna(axis=0, how='all')
stock = stock[~(stock['volume'] == '')]
# step 1 按时间进行倒序排列
stock = stock.sort_values(by=['code','date'], ascending=True)
Util.deleteFile('/result/ZIndexDataBs.csv')
Util.dataFrameToCsv(stock, "/result/ZIndexDataBs.csv", False, stock.columns)














